package com.tsingteng.cosfun.utils;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Environment;
import android.provider.MediaStore;

import com.qiniu.pili.droid.shortvideo.PLDraft;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLShortVideoRecorder;
import com.qiniu.pili.droid.shortvideo.PLVideoFrame;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.bean.JoinCostarBean;
import com.tsingteng.cosfun.bean.VideoSectionBean;
import com.tsingteng.cosfun.ui.costar.CostarActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static android.media.ThumbnailUtils.OPTIONS_RECYCLE_INPUT;

/**
 * 描述: 七牛拍摄的工具类
 * 创建人: 肖利
 * 时间: 2018/8/4
 * qq: (872179966)
 */

public class VideoUtils {
    /**
     * 视屏的专属返回码v
     */
    public static final int VIDEO_CODE_10000 = 10000;
    public static final String VIDEO_STORAGE_DIR = Environment.getExternalStorageDirectory() + "/Cos_fun/";
    public static final String VIDEO_MUSIC = VIDEO_STORAGE_DIR + "/music/";
    public static final String VIDEO_DIVIDE_FILE_PATH = VIDEO_STORAGE_DIR + "divide_composed.mp4";
    public static final String RECORD_FILE_PATH = VIDEO_STORAGE_DIR;
    public static final String EDITED_FILE_PATH = VIDEO_STORAGE_DIR + "edited.mp4";
    public static final String TRIM_FILE_PATH = VIDEO_STORAGE_DIR + "trimmed.mp4";
    public static final String TRANSCODER_PATH = VIDEO_STORAGE_DIR + "tran_scoder.mp4";
    public static final String VIDEO_PATH = "videoPath";//视屏的路径
    public static final String VIDEO_TIME = "videoTime";//视屏的时间
    public static final String VIDEO_MODE_SHOOT = "mode_video_shoot";//是否是嘎评
    public static final String VIDEO_DOWN_FILE = Environment.getExternalStorageDirectory() + "/Cos_fun/down_video/";//合演下载视频的目录
    private static VideoUtils INSTANCE = null;
    private PLShortVideoRecorder mShortVideoRecorder = null;
    private ArrayList<String> pahtList;
    private ArrayList<Long> videoTimeList;
    private int cuttent = -1;
    private JoinCostarBean joinCostarBean;
    private List<VideoSectionBean> videoSectionInfos;
    private boolean isFanPai = false;
    private int playId = -1;
    public static String videoSavePath = VIDEO_STORAGE_DIR + "download/";
    public static String photoSavePathCache = Environment.getExternalStorageDirectory() + "/cache/";

    private ArrayList<Long> videoInfoTimeList = new ArrayList<>();
    private ArrayList<String> videoInfoPathList = new ArrayList<>();

    private static Map<String, String> opuslikeMap = new HashMap<String, String>();//本地喜欢或不喜欢作品
    private static Map<String, String> userguanzhuMap = new HashMap<String, String>();//本地关注或取消关注

    public static Map<String, String> video_grade = new HashMap<String, String>();//本地视频上报记录


    private ArrayList<VideoSectionBean> videoSectionBeanList;
    private String paragraph_id = null;
    private VideoSectionBean videoSectionBean;
    private List<VideoSectionBean> videoSectionInfos1;
    private String audioPath;
    private boolean isResPai;
    private PLDraft plDraft = null;
    private long videoType = -1;
    public static String videoDownPath = Environment.getExternalStorageDirectory()+"/DCIM/Camera/";

    public boolean isResPai() {
        return isResPai;
    }

    public void setResPai(boolean resPai) {
        isResPai = resPai;
    }

    public static void initSdPath() {
        File file = null;
        try {
            file = new File(videoSavePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(VIDEO_DOWN_FILE);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(photoSavePathCache);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {

        }
    }

    private VideoUtils() {
    }


    /**
     * 保存视屏的标志(存video使用)
     *
     * @return
     */
    public long getVideoType() {
        return videoType;
    }

    public void setVideoType(long videoType) {
        this.videoType = videoType;
    }

    public boolean getIsFanPai() {
        return isFanPai;
    }


    public void setFanOan(boolean isFanPai) {
        this.isFanPai = isFanPai;
    }

    public void setVideoAudioPath(String audioPath) {
        this.audioPath = audioPath;
    }

    public String getVideoAudioPath() {
        return audioPath;
    }

    public static VideoUtils getIntance() {
        if (INSTANCE == null) {
            synchronized (VideoUtils.class) {
                if (INSTANCE == null) {
                    INSTANCE = new VideoUtils();
                }
            }
        }
        return INSTANCE;
    }


    public void setmShortVideoRecorder(PLShortVideoRecorder mShortVideoRecorder) {
        this.mShortVideoRecorder = mShortVideoRecorder;
    }

    public PLShortVideoRecorder getmShortVideoRecorder() {
        return mShortVideoRecorder;
    }


    /**
     * 格式化视屏的地址
     *
     * @return
     */
    public String splitVideoName(String name) {
        String[] split = name.split("/");
        if (split.length == 0) return name;
        String s = split[split.length - 1];
        return s;
    }

    public ArrayList<String> getSavePahtList(ArrayList<String> urlList) {
        ArrayList<String> savePath = new ArrayList<>();
        for (int i = 0; i < urlList.size(); i++) {
            savePath.add(splitVideoName(urlList.get(i)));
        }
        return savePath;
    }

    private CommandManager commendManger;

    public void setCommendManger(CommandManager commendManger) {
        this.commendManger = commendManger;
    }

    public CommandManager getCommendManger() {
        return commendManger;
    }


    public void setVideoPath(int index, String path, long time) {
        //为空的话就是异常

        try {
            if (pahtList == null || joinCostarBean == null) return;
            if (index >= pahtList.size()) return;
            pahtList.set(index, path);
            VideoSectionBean videoSectionBean = joinCostarBean.getVideoSectionInfos().get(index);
            videoSectionBean.setOriginalProfileId(joinCostarBean.getProfileId());
            videoSectionBean.setSectionVideoSpan((int) time);
            videoSectionBean.setSectionStartPoint(getHaveTime(index + 1));
            videoSectionBean.setSectionEndPoint((int) (videoSectionBean.getSectionStartPoint() + time));
            videoSectionBean.setFanPan(true);
            videoSectionBean.setSectionVideoUrl(path);
            LogUtils.i("setVideoTimeListsetVideoPath" + index + "=====" + pahtList.size());
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }

    }

    public void addVideoPath(int index, String path, long time) {
        try {
            if (joinCostarBean == null) {
                //为空的话就是说点击的是开拍,初始化视屏的信息
                joinCostarBean = new JoinCostarBean();
                joinCostarBean.setParentVideoId(0);
                videoSectionBeanList = new ArrayList<>();
                joinCostarBean.setVideoSectionInfos(videoSectionBeanList);
                joinCostarBean.setFanPan(true);
            }
            if (pahtList == null) {
                pahtList = new ArrayList<>();
            }
            pahtList.add(index, path);
            //初始化视屏的信息
            VideoSectionBean videoSectionBean = new VideoSectionBean();
            videoSectionBean.setSectionIndex(index);
//        videoSectionBean.setSectionStartPoint(getHaveUseTime()+1);
//        videoSectionBean.setSectionEndPoint((int) (videoSectionBean.getSectionStartPoint()+time));
//        videoSectionBean.setSectionVideoSpan((int) time);
//        videoSectionBean.setOriginalProfileId(joinCostarBean.getProfileId());
//        videoSectionBean.setFanPan(true);
//        videoSectionBean.setSectionVideoUrl(path);
            joinCostarBean.getVideoSectionInfos().add(index, videoSectionBean);
            LogUtils.i("setVideoTimeListsetVideoPath" + index + "=====" + pahtList.size());
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
    }

    public ArrayList<String> getVideoPathList() {
        try {
            if (pahtList == null) return new ArrayList<>();
            LogUtils.i("setVideoTimeListsetgetVideoPathList" + "=====" + pahtList.size());
            return pahtList;
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return new ArrayList<>();
    }

    public String getVideoPath(int index) {
        try {
            if (pahtList == null) return "";
            return pahtList.get(index);
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return "";
    }

    public void destroyVideoList() {
        if (pahtList == null && videoTimeList == null) return;
        if (pahtList != null) {
            pahtList.clear();
            pahtList = null;
        }
        if (videoTimeList != null) {
            videoTimeList.clear();
            videoTimeList = null;
        }
        if (joinCostarBean != null) {
            joinCostarBean = null;
        }

        commendManger = null;


    }

    public void addVideoTimeList(int index, long time) {
        try {
            if (videoTimeList == null) videoTimeList = new ArrayList<>();
            videoTimeList.add(index, time);
            LogUtils.i("setVideoTimeListsetVideoTimeList" + index + "=====" + videoTimeList.size());
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
    }

    public void setVideoTimeList(int index, long time) {
        try {
            if (videoTimeList == null) videoTimeList = new ArrayList<>();
            videoTimeList.set(index, time);
            LogUtils.i("setVideoTimeListsetVideoTimeList" + index + "=====" + videoTimeList.size());
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
    }


    public ArrayList<Long> getVideoTimeList() {
        try {
            if (videoTimeList == null) return new ArrayList<>();
            return videoTimeList;
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return new ArrayList<>();
    }


    public void removeVideo(int index) {
        try {
            if (pahtList == null || pahtList.size() == 0) return;
            if (index >= pahtList.size()) return;
            joinCostarBean.getVideoSectionInfos().remove(index);
            pahtList.remove(index);
            videoTimeList.remove(index);
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
    }

    public long getVideoTime(int index) {
        try {
            if (videoTimeList == null) return 0;
            return videoTimeList.get(index);
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return 0;
    }


    public void setCurremtPosition(int position) {
        cuttent = position;
    }

    public int getCuttentPosition() {
        return cuttent;
    }

    public long getHaveUseTime() {
        try {
            if (videoTimeList == null) return 0;
            long time = 0;
            for (int i = 0; i < videoTimeList.size(); i++) {
                time = time + videoTimeList.get(i);
            }
            return time;
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return 0;
    }

    public long getHaveTime(int index) {
        try {
            if (videoTimeList == null) return 0;
            long time = 0;
            for (int i = 0; i < index; i++) {
                time = time + videoTimeList.get(i);
            }
            return time;
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
        }
        return 0;
    }


    /**
     * 更具地址得到拍摄的图片
     *
     * @param videoPath
     * @return
     */
    public Bitmap getVideoThumbnail(String videoPath) {
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
        if (bitmap != null) {
            return ThumbnailUtils.extractThumbnail(bitmap, 300, 300, OPTIONS_RECYCLE_INPUT);
        }
        return null;
    }


    /**
     * ===================================================================================================================================================
     */

    private ArrayList<String> localList = new ArrayList<>();

    public void setJoinCostarBean(JoinCostarBean joinCostarBean, ArrayList<String> localList) {
        this.joinCostarBean = joinCostarBean;
        this.localList = localList;
        pahtList = new ArrayList<>();
        videoTimeList = new ArrayList<>();
        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        for (int i = 0; i < videoSectionInfos.size(); i++) {
            pahtList.add(VideoUtils.VIDEO_DOWN_FILE + localList.get(i));
            videoTimeList.add((long) (videoSectionInfos.get(i).getSectionVideoSpan()));
            setVideoPath(i, VideoUtils.VIDEO_DOWN_FILE + localList.get(i), videoSectionInfos.get(i).getSectionVideoSpan());
            setVideoTimeList(i, videoSectionInfos.get(i).getSectionVideoSpan());
        }
    }

    public JoinCostarBean getJoinCostarBean() {
        return joinCostarBean;
    }

    /**
     * 添加视频信息
     *
     * @param path
     * @param time
     */
    public void addVideoInfo(String path, long time) {
        addVideoInfo(getVideoInfoSize(), path, time);
    }

    public void addVideoInfo(int index, String path, long time) {
        if (joinCostarBean == null) {
            joinCostarBean = new JoinCostarBean();
            joinCostarBean.setParentVideoId(0);
            videoSectionBeanList = new ArrayList<>();
            joinCostarBean.setVideoSectionInfos(videoSectionBeanList);

        }
        //只要更改了视屏的,就认为是重拍的
        joinCostarBean.setFanPan(true);
        //初始化视屏的信息
        videoSectionBean = new VideoSectionBean();
        videoSectionBean.setSectionIndex(index);
        videoSectionBean.setSectionStartPoint(getVideoInfoTime(index));
        videoSectionBean.setSectionEndPoint((int) (videoSectionBean.getSectionStartPoint() + time));
        videoSectionBean.setSectionVideoSpan((int) time);
        videoSectionBean.setOriginalProfileId(joinCostarBean.getProfileId());
        videoSectionBean.setFanPan(true);
        videoSectionBean.setSectionVideoUrl(path);
        joinCostarBean.getVideoSectionInfos().add(index, videoSectionBean);
        LogUtils.i("videoUtils+ addVideoInfo" + index + "=====" + joinCostarBean.getVideoSectionInfos().size());
    }


    public void setVideoInfo(int index, String path, long time) {
        if (joinCostarBean == null || joinCostarBean.getVideoSectionInfos().size() <= 0 || index >= joinCostarBean.getVideoSectionInfos().size()) {
            return;
        }
        joinCostarBean.setFanPan(true);
        //更爱了视屏的信息住地址就一号改变
        videoSectionBean = joinCostarBean.getVideoSectionInfos().get(index);
        videoSectionBean.setSectionVideoUrl(path);
        videoSectionBean.setFanPan(true);
        videoSectionBean.setSectionEndPoint((int) (videoSectionBean.getSectionStartPoint() + time));
        videoSectionBean.setSectionVideoSpan((int) time);
        LogUtils.i("videoUtils+ setVideoInfo" + "index======" + index + "" + videoSectionBean.getSectionStartPoint() + "======" + videoSectionBean.getSectionEndPoint());
        //然后重置后面视屏的时间
        for (int i = index + 1; i < getVideoInfoSize(); i++) {
            videoSectionBean = joinCostarBean.getVideoSectionInfos().get(index);
            videoSectionBean.setSectionStartPoint(getVideoInfoTime(i));
            videoSectionBean.setSectionEndPoint((int) (videoSectionBean.getSectionStartPoint() + videoSectionBean.getSectionVideoSpan()));
            LogUtils.i("videoUtils+ setVideoInfo" + "index======" + i + "" + videoSectionBean.getSectionStartPoint() + "======" + videoSectionBean.getSectionEndPoint());

        }
    }


    public long getVideoInfoTime() {
        return getVideoInfoTime(getVideoInfoSize());
    }

    public long getVideoInfoTime(int index) {
        long time = 0;
        List<Long> videoInfoTimeList = getVideoInfoTimeList(index);
        for (int i = 0; i < videoInfoTimeList.size(); i++) {
            time = time + videoInfoTimeList.get(i);
        }
        return time;
    }

    public List<Long> getVideoInfoTimeList() {
        return getVideoInfoTimeList(getVideoInfoSize());
    }

    public String getVideoInfoPath() {
        return getVideoInfoPath(getVideoInfoSize() - 1);
    }

    public String getVideoInfoPath(int index) {
        if (joinCostarBean == null) return null;
        videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        return videoSectionInfos.get(index).getLocalUrl();
    }

    public long getSingeVideoInfoTime(int index) {
        if (joinCostarBean == null) return 0;
        return joinCostarBean.getVideoSectionInfos().get(index).getSectionVideoSpan();
    }


    /**
     * 得到video时间的集合
     *
     * @param endIndex
     * @return
     */
    public List<Long> getVideoInfoTimeList(int endIndex) {
        if (videoInfoTimeList == null) new ArrayList<>();
        videoInfoTimeList.clear();
        if (joinCostarBean == null) return videoInfoTimeList;
        videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        for (int i = 0; i < endIndex; i++) {
            videoInfoTimeList.add(Long.valueOf(videoSectionInfos.get(i).getSectionVideoSpan()));
        }
        return videoInfoTimeList;
    }

    /**
     * 得到视屏地址的集合
     *
     * @return
     */
    public ArrayList<String> getVideoInfoPathList() {
        return getVideoInfoPathList(getVideoInfoSize());
    }

    public ArrayList<String> getVideoInfoPathList(int enIndex) {
        if (videoInfoPathList == null) videoInfoPathList = new ArrayList<>();
        videoInfoPathList.clear();
        videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        if (joinCostarBean == null) return videoInfoPathList;
        for (int i = 0; i < enIndex; i++) {
            videoInfoPathList.add(videoSectionInfos.get(i).getSectionVideoUrl());
        }
        return videoInfoPathList;
    }


    public void reMoveVideoInfo(int index) {
        if (joinCostarBean == null || joinCostarBean.getVideoSectionInfos().size() <= 0 || index >= joinCostarBean.getVideoSectionInfos().size()) {
            return;
        }

        List<VideoSectionBean> videoSectionInfos = joinCostarBean.getVideoSectionInfos();
        videoSectionInfos.remove(index);
    }

    public void destoryVideoInfo() {
        joinCostarBean = null;
        commendManger = null;
    }


    /**
     * 得到视频的数量大小
     *
     * @return
     */
    public int getVideoInfoSize() {
        if (joinCostarBean == null) {
            return 0;
        }
        return joinCostarBean.getVideoSectionInfos().size();
    }

    public void setPlayId(int id) {
        this.playId = id;
    }

    public int getPlayId() {
        return playId;
    }


    /**
     * 正常拍摄
     *
     * @param activity
     */
    public void starVideoShoot(Activity activity) {
        playId = -1;
        setVideoType(System.currentTimeMillis());
        destroyVideoList();
        setCommendManger(new CommandManager());
        activity.startActivity(new Intent(activity, CostarActivity.class));
        activity.overridePendingTransition(R.anim.activity_up, R.anim.activity_down_alpha);

    }

    /**
     * 段子翻拍
     *
     * @param activity
     * @param playId
     */
    public void starVideoShootToPlay(Activity activity, int playId) {
        setPlayId(playId);
        setVideoType(System.currentTimeMillis());
        destroyVideoList();
        setCommendManger(new CommandManager());
        activity.startActivity(new Intent(activity, CostarActivity.class));
        activity.overridePendingTransition(R.anim.activity_up, R.anim.activity_down_alpha);
    }


    /**
     * 得到视屏的封面
     *
     * @param videopath
     * @return
     */
    public Bitmap getCoverVideo(String videopath) {
        PLMediaFile plMediaFile = new PLMediaFile(videopath);
        PLVideoFrame videoFrameByIndex = plMediaFile.getVideoFrameByIndex(0, true);
        return videoFrameByIndex.toBitmap();
    }

    /**
     * @param worksId 作品id
     * @param type    0不喜欢 1喜欢
     */
    public static void handelOpusLike(String worksId, String type) {
        try {
            opuslikeMap.put(worksId, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param userId 用户id
     * @param type   0取消关注 1关注
     */
    public static void handelUserGuznZhu(String userId, String type) {
        try {
            userguanzhuMap.put(userId, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取本地喜欢作品数量
    public static int getLocalOpusLikeCount() {
        int likeCount = 0;
        try {

            Set<Map.Entry<String, String>> set = opuslikeMap.entrySet();
            for (Map.Entry<String, String> me : set) {
                String value = me.getValue();
                if ("1".equals(value)) {
                    likeCount++;
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return likeCount;
    }

    //获取本地关注用户数量
    public static int getLocalUserLikeCount() {
        int likeCount = 0;
        try {

            Set<Map.Entry<String, String>> set = userguanzhuMap.entrySet();
            for (Map.Entry<String, String> me : set) {
                String value = me.getValue();
                if ("1".equals(value)) {
                    likeCount++;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return likeCount;
    }

    //获取本地取消关注用户数量
    public static int getLocalUserUnLikeCount() {
        int likeCount = 0;
        try {

            Set<Map.Entry<String, String>> set = userguanzhuMap.entrySet();
            for (Map.Entry<String, String> me : set) {
                String value = me.getValue();
                if ("0".equals(value)) {
                    likeCount++;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return likeCount;
    }
}
